package cn.cloud.all.security.authentication;

import cn.cloud.all.security.core.userdetails.UserCache;
import cn.cloud.all.security.core.userdetails.UserDetails;
import cn.cloud.all.security.core.userdetails.UserDetailsService;
import cn.cloud.all.security.core.userdetails.cache.NullUserCache;
import org.springframework.util.Assert;

public class CachingUserDetailsService implements UserDetailsService {

    private final UserDetailsService delegate;
	private UserCache userCache = new NullUserCache();

    public CachingUserDetailsService(UserDetailsService delegate) {
        this.delegate = delegate;
    }

    public UserDetails loadUserByUsername(String username) {
        UserDetails user = userCache.getUserFromCache(username);

        if (user == null) {
            user = delegate.loadUserByUsername(username);
        }

        Assert.notNull(user, () -> "UserDetailsService " + delegate + " returned null for username " + username + ". " + "This is an interface contract violation");

        userCache.putUserInCache(user);

        return user;
    }
}
